package com.jt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
@Service
public class CartServiceImpl implements DubboCartService {
	
	@Autowired
	private CartMapper cartMapper;

	/**
	 * 购物车数据展现
	 */
	@Override
	public List<Cart> findCartListByUserId(Long userId) {
		QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		return cartMapper.selectList(queryWrapper);
	}

	/**
	 * 购物车数量修改
	 */
	@Override
	public void updateCartNum(Cart cart) {
		Cart cartTemp = new Cart();
		cartTemp.setNum(cart.getNum());
		QueryWrapper<Cart> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", cart.getUserId());
		wrapper.eq("item_id", cart.getItemId());
		cartMapper.update(cartTemp, wrapper);

	}

	/**
	 * 购物车删除操作
	 */
	@Override
	public void deleteCart(Cart cart) {
		QueryWrapper<Cart> wrapper = new QueryWrapper<>(cart);
		cartMapper.delete(wrapper);
	}

	/**
	 * 购物车添加操作
	 */
	@Override
	public void addCart(Cart cart) {
		//查询购物车信息
		QueryWrapper<Cart> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", cart.getUserId())
				.eq("item_id", cart.getItemId());
		Cart cartDB = cartMapper.selectOne(wrapper);
		if(cartDB==null){
			//第一次新增购物车
			cartMapper.insert(cart);
		}else {
			//用户已加购，更新数量
			int num=cartDB.getNum()+cart.getNum();
			Cart cartTemp = new Cart();
			cartTemp.setNum(num)
					.setId(cartDB.getId());
			cartMapper.updateById(cartTemp);
		}
	}

}
